﻿using UnityEditor;
using UnityEngine;

namespace ChivalryUnityEditor
{
    /// <summary>
    /// @Author:Teddy
    /// </summary>
	public class SpriteBindListener : UnityEditor.AssetModificationProcessor
    {
        public delegate void OnMoveAssetEventHandler(string path, string newPath);
        public static event OnMoveAssetEventHandler OnMoveAsset;

        /// <summary>
        /// 移动资源
        /// </summary>
        /// <param name="path"></param>
        /// <param name="newPath"></param>
        /// <returns></returns>
        private static AssetMoveResult OnWillMoveAsset(string path, string newPath)
        {
            if (AssetDatabase.IsValidFolder(path))
            {
                string[] guids = AssetDatabase.FindAssets("", new string[] { path });
                for (int i = 0; i < guids.Length; i++)
                {
                    string assetPath = AssetDatabase.GUIDToAssetPath(guids[i]);
                    string assetNewPath = assetPath.Replace(path, newPath);
                    ModifySprite(assetPath, assetNewPath);
                }
            }
            else
            {
                ModifySprite(path, newPath);
            }
            return AssetMoveResult.DidNotMove;
        }

        /// <summary>
        /// 删除资源
        /// </summary>
        /// <param name="path"></param>
        /// <param name="moveAssetOptions"></param>
        /// <returns></returns>
        private static AssetDeleteResult OnWillDeleteAsset(string path, RemoveAssetOptions moveAssetOptions)
        {
            if (AssetDatabase.IsValidFolder(path))
            {
                string[] guids = AssetDatabase.FindAssets("", new string[] { path });
                for (int i = 0; i < guids.Length; i++)
                {
                    string assetPath = AssetDatabase.GUIDToAssetPath(guids[i]);
                    UnbindSprite(assetPath);
                }
            }
            else
            {
                UnbindSprite(path);
            }
            return AssetDeleteResult.DidNotDelete;
        }

        /// <summary>
        /// 获取绑定路径
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public static string GetBindPath(string path)
        {
            int rawIndex = path.IndexOf("RawResources");
            string bindPath = path.Remove(rawIndex, 3);
            int suffixIndex = bindPath.LastIndexOf('.');
            return bindPath.Remove(suffixIndex + 1) + "prefab";
        }

        /// <summary>
        /// 修改资源
        /// </summary>
        /// <param name="path"></param>
        /// <param name="newPath"></param>
        private static void ModifySprite(string path, string newPath)
        {
            SpriteBindData bindData = LoadBindData();
            if (bindData != null)
            {
                int indexOfPath = bindData.IndexOfPath(path);
                if (indexOfPath != -1)
                {
                    string bindPath = GetBindPath(path);
                    string newBindPath = GetBindPath(newPath);
                    string folderFullPath = newBindPath.Remove(newBindPath.LastIndexOf('/'));
                    new CreateFolderCommand().CreateFolder(folderFullPath, () =>
                    {
                        AssetDatabase.MoveAsset(bindPath, newBindPath);
                    });
                    bindData.RepacePath(indexOfPath, newPath);
                }
            }
            if (OnMoveAsset != null)
            {
                OnMoveAsset(path, newPath);
            }
        }

        /// <summary>
        /// 解绑
        /// </summary>
        /// <param name="path"></param>
        public static void UnbindSprite(string path)
        {
            SpriteBindData bindData = LoadBindData();
            if (bindData == null)
                return;

            if (bindData.RemovePath(path))
            {
                string bindPath = GetBindPath(path);
                AssetDatabase.DeleteAsset(bindPath);
            }
        }

        /// <summary>
        /// 加载绑定数据
        /// </summary>
        /// <returns></returns>
        private static SpriteBindData LoadBindData()
        {
            return Resources.Load<SpriteBindData>("Editor/SpriteBindData");
        }

        public class CreateFolderCommand
        {
            private string m_folderFullPath;
            private System.Action m_callback;

            public void CreateFolder(string folderFullPath, System.Action callback)
            {
                m_folderFullPath = folderFullPath;
                m_callback = callback;
                if (!AssetDatabase.IsValidFolder(folderFullPath))
                {
                    int index = folderFullPath.LastIndexOf('/');
                    string parentFolderPath = folderFullPath.Substring(0, index);
                    string folderPath = folderFullPath.Substring(index + 1);

                    //为了防止父目录不存在,这里必须先创建父目录
                    //真坑爹的Unity!
                    new CreateFolderCommand().CreateFolder(parentFolderPath, () =>
                    {
                        AssetDatabase.CreateFolder(parentFolderPath, folderPath);
                        EditorApplication.update += OnUpdateEditor;
                    });
                }
                else
                {
                    CreateFinish();
                }
            }

            private void OnUpdateEditor()
            {
                if (AssetDatabase.IsValidFolder(m_folderFullPath))
                {
                    CreateFinish();
                }
            }

            private void CreateFinish()
            {
                EditorApplication.update -= OnUpdateEditor;
                if (m_callback != null)
                {
                    m_callback();
                }
            }
        }
    }
}